/**
 * This class allows only one instance of the program to be active through the use of port locking.
 * 
 * 
 */

package org.vt.eldercare.lock;

import java.io.IOException;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;

public class PortLock {

	private static int PORT =9999;  
	@SuppressWarnings("unused")
	private static ServerSocket socket;
	private static byte[] address = {127,0,0,1};
	
	public static void checkRun() {
		checkIfRunning();
	}
	
	private static void checkIfRunning() {
		try {
			socket = new ServerSocket(getPORT(),0,InetAddress.getByAddress(address));
			}
		catch (BindException e) {
		    System.err.println("Already running.");
		    System.exit(1);
		  }
		  catch (IOException e) {
		    System.err.println("Unexpected error.");
		    e.printStackTrace();
		    System.exit(2);
		  }
}
	public static int getPORT() {
		return PORT;
	}

	public static void setPORT(int Port) {
		PORT = Port;
	}
}
